package com.wushi.lenovo.asia5b.app_ui.other.dialog.trans;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseDialogFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_http.TopupService;
import com.wushi.lenovo.asia5b.app_model.other.TransItemBean;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ForgotPayPassDialog;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.FirstPayPassActivity;
import com.wushi.lenovo.asia5b.app_widget.pass.PayPwdEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhangyuncai on 2019/11/20.
 * 用于输入支付密码的dialog
 */
public abstract class PayDialogFragment extends BaseDialogFragment {
    @BindView(R.id.tv_ctransfer_confirm)
    TextView tv_ctransfer_confirm;//
    @BindView(R.id.tv_ctransfer_1)
    TextView tv_ctransfer_1;
    @BindView(R.id.paypwd_ctarnsfer)
    PayPwdEditText paypwd_ctarnsfer;//密码
    @BindView(R.id.bt_ctransfer_submit)
    Button bt_ctransfer_submit;//提交
    @BindView(R.id.tv_ctrans_pass_error)
    TextView tv_ctrans_pass_error;
    @BindView(R.id.ll_trans_notice_vessel)
    LinearLayout ll_trans_notice_vessel;
    @BindView(R.id.iv_trans_noticeicon)
    ImageView iv_trans_noticeicon;
    @BindView(R.id.tv_trans_notice)
    TextView tv_trans_notice;
    @BindView(R.id.rv_transfer)
    RecyclerView mRecyclerView;
    TransAdapter mAdapter;
    protected final List<TransItemBean> mDatas = new ArrayList<>();
    protected final ApiService apiService = NetworkModule.getRetrofit().create(ApiService.class);
    protected final TopupService topupService = NetworkModule.getRetrofit().create(TopupService.class);

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_pay;
    }

    @Override
    protected void initView() {

        paypwd_ctarnsfer.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.common_text_black, R.color.common_text_black, 20);
        mAdapter = new TransAdapter(mDatas);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        onFilterDoubleClick(bt_ctransfer_submit, v -> checkPayPass());
        paypwd_ctarnsfer.setOnTextChangeListener(content -> {
            tv_ctrans_pass_error.setVisibility(View.INVISIBLE);
        });
    }

    @OnClick({
            R.id.tv_ctransfer_forgot,
            R.id.ll_trans_notice_vessel,
            R.id.tv_tag_close
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_trans_notice_vessel:
                break;
            case R.id.tv_ctransfer_forgot://忘记密码
                if (UserInfo.getUserInfo().getHas_pay_pass()) {
                    ForgotPayPassDialog forgotPayPassDialog = new ForgotPayPassDialog(mContext);
                    forgotPayPassDialog.show();
                } else {
                    startActivity(new Intent(mContext, FirstPayPassActivity.class));
                }
                break;
            case R.id.tv_tag_close://关闭
                dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 提交支付第一步骤:检测支付密码是否有效,有效则返回该支付密码
     * 该用户是否有支付密码 && 支付密码符合规则
     */
    protected void checkPayPass() {
        if (!UserInfo.getUserInfo().getHas_pay_pass()) {

            new AlertDialog.Builder(getContext())
                    .setTitle(R.string.not_paypss)
                    .setNegativeButton(R.string.cancel, null)
                    .setPositiveButton(R.string.set_paypss, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getContext().startActivity(new Intent(getContext(), FirstPayPassActivity.class));
                        }
                    })
                    .create().show();
        }
        String pwdText = paypwd_ctarnsfer.getPwdText();
        if (!TextUtils.isEmpty(pwdText) && pwdText.length() == 6) {
            submit(pwdText);
        }
    }

    /**
     * 调用提交的接口
     *
     * @param payPass
     * @return
     */
    protected abstract Observable<ResultModel> getSubmitObservable(String payPass);

    /**
     * 调用提交回调的接口
     *
     * @return
     */
    protected abstract Consumer<ResultModel> getSubmitResult();

    /**
     * 提交支付
     */
    protected void submit(String payPass) {
        Disposable subscribe = apiService.checkPayPass(UserInfo.getMemberId(), payPass)
                .flatMap(new Function<ResultModel, ObservableSource<ResultModel>>() {
                    @Override
                    public ObservableSource<ResultModel> apply(ResultModel resultModel) throws Exception {
                        if (resultModel.isSuccess()) {
                            /**
                             * 从子dialog拿到提交接口
                             */
                            return getSubmitObservable(payPass);
                        } else {
                            resultModel.setResult(2);
                        }
                        return Observable.just(resultModel);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    showLoadingBar(null);
                })
                .doAfterTerminate(() -> {
                    dismissLoadingBar("");
                })
                .subscribe(resultModel -> {

                    paypwd_ctarnsfer.clearText();
                    if (resultModel.getResult() == 2) {
                        //密码错误
                        tv_ctrans_pass_error.setVisibility(View.VISIBLE);
                        ToastUtil.showToast(resultModel.getMsg());
                    } else {//密码正确,但其他错误
                        if (!resultModel.isSuccess()) {
                            ToastUtil.showToast(resultModel.getMsg());
                        } else {
                            if (callBack != null) {
                                callBack.callback(resultModel);
                            }
                        }
                        //回调给子dialog
                        getSubmitResult().accept(resultModel);
                        payResult(resultModel.isSuccess());
                    }

                }, throwable -> {
                    throwable.printStackTrace();
                });
        composite.add(subscribe);
    }


    /**
     * 支付结果
     *
     * @param isSuccess 是否成功
     */
    protected void payResult(boolean isSuccess) {
        bt_ctransfer_submit.setText(R.string.ok);
        bt_ctransfer_submit.setOnClickListener(v -> {
            dismiss();
        });
    }

    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }

    @Override
    protected int getWidthStyle() {
        return getScreenWidth(0.9f);
    }

    @Override
    protected boolean isCancelableOutside() {
        return false;
    }
}
